<?php

	// read the post from PayPal system and add 'cmd'
	$req = 'cmd=_notify-validate';
	
		foreach ($_POST as $key => $value) {
			$value = urlencode(stripslashes($value));
			$req .= "&$key=$value";
		}
	
	// post back to PayPal system to validate
	$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
	$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30); 
	//$fp = fsockopen ('www.eliteweaver.co.uk', 80, $errno, $errstr, 30);
	
	// assign posted variables to local variables
	$item_name 			= $_POST['item_name'];
	$intAuctionID 		= $_POST['item_number'];  
	 
		if($intAuctionID == 0 ){   
			fclose ($fp);
			exit();
		}				
		
	$strPaymentStatus	= $_POST['payment_status'];
	$intPaymentAmount 	= $_POST['mc_gross'];
	$intItemPayment 	= $_POST['mc_gross'] - $_POST['shipping'];
	$payment_currency 	= $_POST['mc_currency'];	 
	$intCarriagePaid 	= $_POST['shipping'];
	$intPayPalTXNID 	= $_POST['txn_id'];
	$receiver_email 	= $_POST['receiver_email'];
	$payer_email 		= $_POST['payer_email']; 
	$strFirstName		= $_POST['first_name'];
	$strSurname			= $_POST['last_name'];	  
	$strPurchaserEbayID	= $_POST['auction_buyer_id'];
	$strCompanyName 	= $_POST['payer_business_name'];
	$strAddress1 	 	= $_POST['address_street'];
	$strTown 			= $_POST['address_city'];
	$strCounty 			= $_POST['address_state'];
	//$address_country 	= $_POST['address_country'];
	$strPostalCode		= $_POST['address_zip'];		  
	$intPayPalFee 		= $_POST['mc_fee'];	
	$strEmail			= $_POST['payer_email'];	  
	$intTitle 			= 9;						//set purchaser title to NA	   

		if ($strPaymentStatus == "Completed"){
			$intEbayStatus = 4; //Paid
		}else{
		 	$intEbayStatus = 111;	  //Paypal error
		}
	
	
		if($_POST['address_country_code'] ==	"GB"){
			  $intCountry = 202;
		}
	
		while (list($name, $value) = each($HTTP_POST_VARS)) {
		
		    $strPostedVars .= "$name = $value<br>\n";
		
		}
		
		//Calculate Commission
		if($intItemPayment <= 10){
			$intPayVendor = 0;
			$intOurCommission = $intItemPayment;
			
		}
		
		if(($intItemPayment > 10) && ($intItemPayment <= 30)){
			$intPayVendor = $intItemPayment - 10;
			$intOurCommission = 10;
		}
		
		if($intItemPayment > 30){
			$intPayVendor = number_format((($intItemPayment / 3) * 2), 2, '.', '');
			$intOurCommission = number_format($intItemPayment / 3, 2, '.', '');
		}
		
	$txtPayUs = $intOurCommission + $intCarriagePaid - $intPayPalFee;

	$strFromEmail = "paypal@delboyslockup.co.uk";
	$strFromName = "PayPal IPN";
	$strToEmail = "paypal@delboyslockup.co.uk";
	
	//see if txn has been processed before
	$strSelectSQL = "SELECT * FROM tblAuctionItem WHERE AuctionID = '".$intAuctionID."' AND PayPalTXN  = '".$intPayPalTXNID."'";	
					
	$strUpdateSQL = "Update tblAuctionItem
                 SET   tblAuctionItem.ReceivedPayment =  '1'
				 	 , tblAuctionItem.AuctionSellingFee  = '".$intItemPayment."'
					 , tblAuctionItem.OurCommission   = '".$intOurCommission."'
					 , tblAuctionItem.PayVendor    = '".$intPayVendor."'
					 , tblAuctionItem.PayUs     = '".$txtPayUs."'
                     , tblAuctionItem.PayPalTXN =  '".$intPayPalTXNID."'
		 			 , tblAuctionItem.PayPalFee =  '".$intPayPalFee."'
		 			 , tblAuctionItem.CarriagePaid =  '".$intCarriagePaid."'
					 , tblAuctionItem.DatePaid =  now()
                     , tblAuctionItem.PurchaserEbayID =  '".$strPurchaserEbayID."' 
					 , tblAuctionItem.EbayStatus =  '".$intEbayStatus."'
					 , tblAuctionItem.Title =  '".$intTitle."'
                     , tblAuctionItem.CompanyName =  '".$strCompanyName."'
                     , tblAuctionItem.FirstName =  '".$strFirstName."'
                     , tblAuctionItem.Surname =  '".$strSurname."'
                     , tblAuctionItem.Address1 =  '".$strAddress1."'
                     , tblAuctionItem.Address2 =  '".$strAddress2."'
                     , tblAuctionItem.Town =  '".$strTown."'
                     , tblAuctionItem.County =  '".$strCounty."'
                     , tblAuctionItem.PostalCode =  '".$strPostalCode."'
                     , tblAuctionItem.Country =  '".$intCountry."'
                     , tblAuctionItem.Phone =  '$strPhone'
                     , tblAuctionItem.Email =  '$strEmail'
					 , tblAuctionItem.BackgroundHistory = '".$strPostedVars."'
				WHERE AuctionID = '".$intAuctionID."'";

		if (!$fp) {	  
			
		// HTTP ERROR
		} else {
			fputs ($fp, $header . $req);
				while (!feof($fp)) {
					$res = fgets ($fp, 1024);
					if (strcmp ($res, "VERIFIED") == 0) {
						
						$strSubject = SITE_NAME." : PayPal IPN test Verified";	 
						
						// check the payment_status is Completed  
						if ($strPaymentStatus == "Completed"){
							$strSQL = $strSelectSQL;
							include (MODULE . "/action/actMySqlResults"); 
							$strSQL = "";
							// check that txn_id has not been previously processed 
							
								if($myrow[0]){
									// add processing to change status to needs looking at
									// as TXN as previously been processed
									$strMessageBody = "Previously processed";  
									SendMime($strSubject, $strMessageBody, $strToEmail, $strFromEmail, $strFromName,$strHeader);
								}else{
								 	// check that receiver_email is your Primary PayPal email
									// check that payment_amount/payment_currency are correct
									// process payment
									//Add payment details to database
									$strSQL = $strUpdateSQL;
									include (MODULE . "/action/actMySqlResults"); 
									$strSQL = "";
									$strMessageBody = "VERIFIED<br>
														$strPostedVars
														<br>item_name $item_name <br>
														item_number $intAuctionID <br>
														payment_status $strPaymentStatus<br>
														payment_amount $intPaymentAmount <br>	 
														payment_fee $intPayPalFee <br>
														payment_currency $payment_currency <br>
														txn_id $intPayPalTXNID <br>
														receiver_email $receiver_email <br>
														payer_email $payer_email <br>
														strFromEmail $strFromEmail <br>	
														".$first_name."&nbsp;".$last_name."<br>".
														$strCompanyName."<br>".
														$strAddress1."<br>".
														$strTown."<br>".
														$strCounty."<br>".
														$address_country."<br>".
														$strPostalCode."<br><br>".
														$strSelectSQL."<br>".$strUpdateSQL;		 
									
														
									$strUpdateSQL = "Update tblAuctionItem
	                 			SET   tblAuctionItem.BackgroundHistory  =  '".$strMessageBody."'
								WHERE AuctionID = '".$intAuctionID."'";	   
							$strSQL = $strUpdateSQL;
												SendMime($strSubject, $strMessageBody, $strToEmail, $strFromEmail, $strFromName,$strHeader);
								}
						
						}else{
							 // add processing to change status to "PayPal payment incomplete"
							 //$strMessageBody = "Status not Completed"; 	
							 $strMessageBody = "VERIFIED Status not Completed<br>
														$strPostedVars
														<br>item_name $item_name <br>
														item_number $intAuctionID <br>
														payment_status $strPaymentStatus<br>
														payment_amount $intPaymentAmount <br>	 
														payment_fee $intPayPalFee <br>
														payment_currency $payment_currency <br>
														txn_id $intPayPalTXNID <br>
														receiver_email $receiver_email <br>
														payer_email $payer_email <br>
														strFromEmail $strFromEmail <br>	
														".$first_name."&nbsp;".$last_name."<br>".
														$strCompanyName."<br>".
														$strAddress1."<br>".
														$strTown."<br>".
														$strCounty."<br>".
														$address_country."<br>".
														$strPostalCode."<br><br>".
														$strSelectSQL."<br>".$strUpdateSQL;		
	
							SendMime($strSubject, $strMessageBody, $strToEmail, $strFromEmail, $strFromName,$strHeader);
	
						}
					
					
				
					}else if (strcmp ($res, "INVALID") == 0) {
						// log for manual investigation			
						//echo "invalid";
						
						$strMessageBody = "INVALID<br>
										$strPostedVars<br>
										item_name $item_name <br>
										item_number $intAuctionID <br>
										payment_status $strPaymentStatus<br>
										payment_amount $intPaymentAmount <br>	 
										payment_fee $intPayPalFee <br>
										payment_currency $payment_currency <br>
										txn_id $intPayPalTXNID <br>
										receiver_email $receiver_email <br>
										payer_email $payer_email <br>
										strFromEmail $strFromEmail <br>	
										".$first_name."&nbsp;".$last_name."<br>".
										$strCompanyName."<br>".
										$strAddress1."<br>".
										$strTown."<br>".
										$strCounty."<br>".
										$address_country."<br>".
										$strPostalCode."<br><br>".
										$strSelectSQL."<br>".$strUpdateSQL;		
						$strFromEmail = "paypal@delboyslockup.co.uk";
						$strFromName = "PayPal IPN";
						$strToEmail = "paypal@delboyslockup.co.uk";
						$strSubject = SITE_NAME." : PayPal IPN test Invalid";					  
	
						include (MODULE . "/action/actMySqlResults"); 
						$strSQL = "";
						SendMime($strSubject, $strMessageBody, $strToEmail, $strFromEmail, $strFromName,$strHeader);
	
					}
				}
				fclose ($fp);
			}
?>
